package org.kcloud.webgate;

import org.gtiles.components.configuration.LoginConfigurationProperties;
import org.gtiles.components.login.authentication.CustomAuthenticationUserDetailsService;
import org.gtiles.components.login.handler.CustomAuthenticationFailureHandler;
import org.gtiles.components.login.handler.CustomAuthenticationSuccessHandler;
import org.gtiles.components.login.handler.CustomLogoutSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
	// @Bean
	// public CustomAuthenticationUserDetailsService customUserService() {
	// return new CustomAuthenticationUserDetailsService();
	// }
	//
	// @Override
	// protected void configure(AuthenticationManagerBuilder auth)
	// throws Exception {
	// }
	@Bean
	public LoginConfigurationProperties loginConfigurationProperties() {
		return new LoginConfigurationProperties();
	}
	@Bean
	@Override
	protected UserDetailsService userDetailsService() {
		// InMemoryUserDetailsManager manager = new
		// InMemoryUserDetailsManager();
		// manager.createUser(User.withUsername("user_1").password("123456")
		// .authorities("USER").build());
		// manager.createUser(User.withUsername("user_2").password("123456")
		// .authorities("USER").build());
		// return manager;
		return new CustomAuthenticationUserDetailsService();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// @formatter:off
		http.authorizeRequests().anyRequest().authenticated()
				.antMatchers("/login", "/logout")
				.permitAll()
				.and()
				.csrf()
				.disable()
				// .addFilterBefore(new CustomLoginPageGeneratingFilter(),
				// DefaultLoginPageGeneratingFilter.class)
				.formLogin()
				.successHandler(new CustomAuthenticationSuccessHandler(loginConfigurationProperties()))
				.failureHandler(new CustomAuthenticationFailureHandler())
				.and().logout()
				.logoutSuccessHandler(new CustomLogoutSuccessHandler());
		// @formatter:on
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/portal/**", "/adminconsole/**",
				"/workbench/**", "/zuul/**","/zuul/api-*/workbench/**", "/zuul/workbench/**", "/**/*.css",
				"/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.gif",
				"/**/fonts/**", "/page/**", "/components/**", 
				"/mobile/portal/**", "/api-*/workbench/**", "/api-*/portal/open/**",
				"/api-*/mobile/open/**");
	}
}